from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re
#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def getCookies(keyword):

    headers = {
        'Origin': 'http://cpem.cp.com.cn',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html, */*; q=0.01',
        'Referer': 'http://cpem.cp.com.cn/Search',
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
    }

    data = {
        'searchValue': keyword,
        'instanceKey': 'FullText'
    }
    s = requests.session()
    s.post('http://cpem.cp.com.cn/Search/BasicSearch', headers=headers, data=data)
    requests.cookies.RequestsCookieJar()  # 利用RequestsCookieJar获取cookies
    cookies = s.cookies.get_dict()

    return cookies


def getId(type,dd):

    #类型对应的详情id，后面继续完善
    typeCorrId = {
        "perio" : "article_id"
    }

    return dd[typeCorrId[type]]

def formData(response):
    allData = []
    lis = response.json()["data"]
    allNum = response.json()["total"]

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li["Title"]
        except:
            pass
        try:
            tempData["titleHref"] = "http://cpem.cp.com.cn/Detail" + li["EncodedID"]
        except:
            pass

        try:
            tempData["author"] = [li["AuthorName"]]
        except:
            pass

        try:
            tempData["publishTime"] = li["PublicationDate"]
        except:
            pass

        allData.append(tempData)

    return allData

def buildingParameters(data):
    # 主题、题名或关键词、题名、第一作者、作者单位、作者、关键词、摘要、基金、DOI
    # 主题:()*作者:()
    typeCorr = {
        "SU": "主题",
        "TI": "题名",
        "AU": "作者",
        "AF": "作者单位",
        "AB": "摘要",
        "KY": "关键词",
    }
    logCorr = {
        "and": "*",
        "or": "+",
        "not": "^",
        "###":"###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            strr = typeCorr[data["type"][i]] + ":" + "(" + data["values"][i] + ")" + "{}".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            continue

    strr = ''
    for value in tempStr:
        strr += value

    return strr.strip().strip("#").strip()


def getData(cookies):


    headers = {
        'Origin': 'http://cpem.cp.com.cn',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/plain, */*; q=0.01',
        'Referer': 'http://cpem.cp.com.cn/Search',
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
    }

    params = (
        ('ResultGrid-size', '20'),
    )

    data = {
        'page': '1',
        'size': '20'
    }

    response = requests.post('http://cpem.cp.com.cn/Search/ResultTable', headers=headers, params=params,data=data,cookies=cookies)

    result = formData(response)


    return result

def index(request):
    data = json.loads(request.POST.get('data', '1'))
    # paramStrs = buildingParameters(data)
    cookies = getCookies(data["values"][0])

    allData = getData(cookies)

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")
